package com.cyy.utils;

import com.cyy.contanst.GlobalVar;
import io.appium.java_client.touch.offset.PointOption;
import io.cucumber.datatable.DataTable;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Component;

import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class Common {

    public String get_project_path() {
        return System.getProperty("user.dir");
    }

    public void sleep(int mills) {
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 对table中的每个变量进行遍历，如果变量中的值也有${name}的变量，替换
     *
     * @param table cucumber table变量
     * @return
     */
    public List<Map<String, Object>> replaceTable(DataTable table) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> maps = table.asMaps(String.class, Object.class);

        maps.forEach(map -> {
            Map<String, Object> one = new HashMap<>();
            for (String key : map.keySet()) {
                Object value = map.get(key);
                Object replaceValue = replace(value.toString());
                one.put(key, replaceValue);
            }
            result.add(one);
        });

        return result;

    }

    /**
     * 生成uuid
     *
     * @param sep 分隔符
     * @return
     */
    public String uuid(String sep) {
        String uuid = UUID.randomUUID().toString().replace("-", sep);
        return uuid;
    }


    public String today() throws ParseException {
        return today("yyyy-MM-dd");
    }

    public String today(String format) throws ParseException {
        String date = today_delta(format, 0, 0);
        return date;
    }

    public int randInt(int start, int end) {
        Random random = new Random();
        int rndint = random.nextInt(end - start);
        return rndint + start;
    }

    public String today_delta(String format, int delta, int field) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.ENGLISH);//设定格式
        Calendar instance = Calendar.getInstance();
        instance.add(field, delta);
        return simpleDateFormat.format(instance.getTime());
    }

    /**
     * 使用正则表达式的方式在字符串source中查找匹配的对象
     *
     * @param source 字符串
     * @param regx   正则表达式
     * @return 返回相匹配的字符串，没有匹配对象返回null
     */
    public String findstr(String source, String regx) {
        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(source);
        if (matcher.find()) return matcher.group();
        return null;
    }

    public Map entity2map(Object bean) {
        Map map = new HashMap();
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.entrySet().forEach(key -> map.put(key, beanMap.get(key)));
        return map;
    }

    /**
     * 对表格数据中的数据解析，如果变量格式出现${name}，使用property下的变量进行替换
     *
     * @param table
     */
    public List<Map<Object, Object>> datatableRep(DataTable table) {
        List<Map<Object, Object>> maps = new ArrayList<>();
        // 替换
        List<Map<Object, Object>> table_maps = table.asMaps(Object.class, Object.class);

        for (Map<Object, Object> table_map : table_maps) {
            Map<Object, Object> one_map = new HashMap<>();
            table_map.keySet().forEach(k -> {
                one_map.put(k.toString(), replace(table_map.get(k.toString()).toString()));
            });
            maps.add(one_map);
        }
        return maps;

    }

    /**
     * 替换变量中的值如果变量的格式为${name}的格式
     *
     * @param value 变量
     * @return
     */
    public String replace(String value) {
        String replace = new StringSubstitutor(GlobalVar.value).replace(value);
        return replace;
    }

    /**
     * byte对象保存到本地
     *
     * @param data byte图片数据
     * @param path 本地保存路径
     */
    public void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals("")) return;
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            System.out.println("Make Picture success,Please find image in " + path);
        } catch (Exception ex) {
            System.out.println("Exception: " + ex);
            ex.printStackTrace();
        }
    }

    /**
     * 查询指定文件夹下后缀名为suffix的文件
     *
     * @param folder 文件夹路径
     * @param suffix 后缀
     * @return 所有符合条件的文件的路径名集合, 没有符合条件的文件则返回空集合
     */
    public List<String> find_files(String folder, String suffix) {
        List<String> files = new ArrayList<>();
        File folderobj = new File(folder);
        File[] all = folderobj.listFiles();
        for (File file : all) {
            if (file.getName().endsWith(suffix)) {
                files.add(file.getAbsolutePath());
            }
        }
        return files;
    }

    /**
     * 已知圆心坐标和半径，计算⚪边上的点坐标
     * @param x 圆心x坐标
     * @param y 圆心y坐标
     * @param r 圆半径
     * @return
     */
    public LinkedList<PointOption> get_points_circle(float x, float y, float r, int num) {
        LinkedList<PointOption> points = new LinkedList<>();
        for (int i = 0; i < num; i += 1) {
            int x1 = (int) (x - r * Math.sin(Math.PI * (i - 90) / (num/2)));
            int y1 = (int) (y - r - 10 + r * Math.cos(Math.PI * (i - 90) / (num/2)));
            points.add(PointOption.point(x1,y1));
        }
        return points;
    }

    public static void main(String[] args) throws ParseException {
        Common common = new Common();
//        String old = "你的姓名:${姓名},${age}";
//        GlobalVar.value.put("姓名","zhupingkai");
//        GlobalVar.value.put("age","12");
//        System.out.println(common.replace(old));

//        List<String> files = common.find_files(System.getProperty("user.dir") + "/report/cucumber-reports", "json");
//        for (String file : files) {
//            System.out.println("---> " + file);
//        }
        LinkedList<PointOption> points_circle = common.get_points_circle(640, 360, 320, 10);
        points_circle.forEach(p -> {
            System.out.println(p.build());
        });

        System.out.println("----------------------");

        Collections.shuffle(points_circle);
        points_circle.forEach(p -> {
            System.out.println(p.build());
        });

    }

}
